import time
import re

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from flask_cors import CORS
from flask import Flask, request, json

app = Flask('baidu-routing-service')
CORS(app)


def createChromeDriver():
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    # 将--user-data-dir改为自定义目录
    # 在linux服务器上执行，需要增加
    # chrome_options.add_argument("--user-data-dir=/root")

    s = Service(executable_path='/Users/gilbert/chromedriver-mac-x64/chromedriver')
    _chrome_driver_instance = webdriver.Chrome(service=s, options=chrome_options)

    _chrome_driver_instance.maximize_window()

    return _chrome_driver_instance


def scrapyBaiduRoute(source, destination):
    chrome_driver_instance = createChromeDriver()

    try:
        chrome_driver_instance.get("https://map.baidu.com/")

        time.sleep(2)

        chrome_driver_instance.find_element(By.XPATH, "//div[@id='searchbox-container']"
                                                      "//div[@data-title='路线']").click()

        time.sleep(2)

        chrome_driver_instance.find_element(By.XPATH,
                                            "//input[contains(@class, 'route-start-input')]").clear()

        time.sleep(2)

        chrome_driver_instance.find_element(By.XPATH,
                                            "//input[contains(@class, 'route-start-input')]").send_keys(source)

        time.sleep(5)

        chrome_driver_instance.find_element(By.XPATH, "//div[@id='ui3-suggest-scroll'][1]").click()

        time.sleep(2)

        chrome_driver_instance.find_element(By.XPATH, "//input[@class='route-end-input']").send_keys(destination)

        time.sleep(2)

        chrome_driver_instance.find_element(By.XPATH, "//button[@id='search-button']").click()

        time.sleep(2)

        chrome_driver_instance.find_element(By.XPATH, "//div[@class='route-header']//span[text()='驾车']").click()

        time.sleep(2)

        pcUrl = chrome_driver_instance.current_url

        match = re.search(r'(.*?querytype=nav)(.*)', pcUrl)
        new_string = 'https://map.baidu.com/mobile/webapp/drive/list/qt=nav'
        if match:
            replaced_string = new_string + match.group(2)[match.start(1):]

            chrome_driver_instance.get(replaced_string)

            time.sleep(2)

            chrome_driver_instance.find_element(By.XPATH, "//a[text()='地图']").click()

            time.sleep(2)

            return chrome_driver_instance.current_url
        else:
            print("未找到指定的字符串")

            return ''

    except Exception as e:
        print(e.__str__())

        return ''
    finally:
        chrome_driver_instance.quit()


@app.route('/getRoutes', methods=['GET'])
def getRoutes():
    data = json.loads(json.dumps(request.get_json()))

    return scrapyBaiduRoute(data['start'], data['end'])


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=10010, debug=False)
